package com.itheima.youdianda.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.youdianda.common.R;
import com.itheima.youdianda.entity.SysUser;
import com.itheima.youdianda.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/sys_user")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 用户列表-分页
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/list")
    public R<Page> list(int page, int limit){
        //创建分页构造器
        Page<SysUser> pageInfo = new Page<>(page,limit);
        //创建条件构造器
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        //添加排序条件
        queryWrapper.orderByAsc(SysUser::getUpdate_date);
        //分页查询
        sysUserService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }


    /**
     * 管理员添加
     * @param sysUser
     * @return
     */
    @PostMapping("/add")
    public R<String> add(@RequestBody SysUser sysUser){
        log.info("要添加的管理员信息为{}",sysUser.toString());
        sysUserService.save(sysUser);
        return R.success("添加成功");
    }


    /**
     * 管理员详情,用于管理员修改的数据回显
     * @param id
     * @return
     */
    @GetMapping("/rowInfo")
    public R<SysUser> rowInfo(@RequestParam String id){
        log.info("管理员的id为{}",id);
        //添加条件构造器
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getId,id);
        SysUser user = sysUserService.getOne(queryWrapper);
        return R.success(user);
    }


    /**
     * 管理员修改
     * @param sysUser
     * @return
     */
    @PostMapping("/update")
    public R<String> update(@RequestBody SysUser sysUser){
        log.info("要修改的管理员信息为:{}",sysUser.toString());
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getId,sysUser.getId());
        sysUserService.update(sysUser,queryWrapper);
        return R.success("修改成功");
    }


    /**
     * 管理员删除
     * @param id
     * @return
     */
    @GetMapping("/del")
    public R<String> del(@RequestParam String id){
        log.info("要删除的管理员id为:{}",id);
        //添加条件构造器
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getId,id);
        sysUserService.remove(queryWrapper);
        return R.success("删除成功");
    }
}
